<?php

/**
 * Created by PhpStorm.
 * User: xuezhileikaku
 * Email:chengyingbo88@163.com
 * Date: 2024/8/23
 * Time: 下午6:36
 */

namespace App\Routing;

use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\RequestHandlerInterface;
use GuzzleHttp\Psr7\Response;

class Router implements RequestHandlerInterface
{
    private $routes = [];

    public function addRoute(string $method, string $path, callable $handler): void
    {
        $this->routes[$method][$path] = $handler;
    }

    public function handle(RequestInterface $request): ResponseInterface
    {
        $method = $request->getMethod();
        $path = $request->getUri()->getPath();

        if (isset($this->routes[$method][$path])) {
            return call_user_func($this->routes[$method][$path], $request);
        }

        return new Response(404, [], 'Not Found');
    }
}
